Array.prototype.put = function (value) {
    if (!this.includes(value)) {
        this.push(value);
    }
};
Array.prototype.remove = function (value) {
    let index = this.indexOf(value);
    if (index > -1) {
        this.splice(index, 1);
    }
};
Date.prototype.format = function(pattern){
    let option = {
        'Y' : this.getFullYear().toString(),
        'm' : (this.getMonth() + 1).toString(),
        'd' : this.getDate().toString(),
        'h' : this.getHours().toString(),
        'i' : this.getMinutes().toString(),
        's' : this.getSeconds().toString()
    };
    option.y = option.Y.substr(2,2);
    option.M = option.m.length < 2 ? '0' + option.m : option.m;
    option.D = option.d.length < 2 ? '0' + option.d : option.d;
    option.H = option.h.length < 2 ? '0' + option.h : option.h;
    option.I = option.i.length < 2 ? '0' + option.i : option.i;
    option.S = option.s.length < 2 ? '0' + option.s : option.s;

    let buffer = '';
    pattern = pattern.split('');
    pattern.forEach(function (key) {
        if (typeof(option[key]) === 'undefined') {
            buffer += key;
        } else {
            buffer += option[key];
        }

    });
    return buffer;
};

//系统全局属性
let system = {
    url: '/',
    token: '',
    socket: 'wss://192.168.1.110/wss',
    ice_server: [{urls: 'stun:118.101.12.12:3478'}, {urls: ['turn:118.101.12.12:3478?transport=udp'], username: 'eqphp', credential: '123456'}],
    error: ['操作成功', '错误的请求方式', '应用程序版本不匹配', '未被授权，请登录', 'Token失效，请退出重新登录', '未定义的请求方式', '项目配置有误，请联系管理员', '服务端代码编译出错，请联系管理员', '', '']
};

//正则表达式
const regexp = {
    phone: /^(1(([389][0-9])|(4[5,7])|(5[^4])|(66)|(7[03678])))\d{8}$/,
    email: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
    telephone: /^(0\d{2,3})?-?([2-9]\d{6,7})(-\d{1,5})?$/,
    hot_line: /^(400|800)-(\d{3})-(\d{4})?$/,
    qq: /^[1-9]\d{4,9}$/,
    account: /^[a-zA-Z][a-zA-Z0-9_]{4,17}$/,
    md5: /^[a-f0-9]{32}$/,
    password: /^(.){6,18}$/,
    money: /^[0-9]+([.][0-9]{1,2})?$/,
    number: /^[+-]?[0-9]*\.?[0-9]*$/,
    numeric: /^\d+$/,
    alpha: /^[a-zA-Z]+$/,
    alpha_numeric: /^[a-zA-Z0-9]+$/,
    alpha_numeric_dash: /^[a-zA-Z0-9_]+$/,
    captcha: /^[a-z0-9]{4,5}$/,
    message_code: /^[1-9]\d{3,5}$/,
    trade_no: /^\d{18}$/,
    card_no: /^[6,8]\d{11}$/,
    coupon_code: /^[123]\d{9}$/,
    url: /^http(s?):\/\/([\w-]+\.)+[\w-]+(\/[\w\- .\/?%&=]*)?/,
    cid: /^\d{15}$|^\d{17}(\d|X|x)$/,
    address: /^(.){0,196}$/,
    int: /^[+-]?\d+$/,
    float: /^[+-]?\d+(\.\d+)?$/,
    chinese: /^[\u4E00-\u9FA5]+$/,
    chinese_name: /^[\u4E00-\u9FA5]{2,5}$/,
    name: /^[\u4E00-\u9FA5\uf900-\ufa2d\w]+$/,
    file_name: /^[^\/:*?"<>|,\\]+$/,
    id: /^[1-9][0-9]{0,9}$/,
    uuid: /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/,
    image: /<img[^\/>src]+src="([^"]+)"[^\/>]*\/?/,
    business_license: /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/
};

//定义cookie对象
const cookie = {
    get: function (name) {
        let temp,cva = [];
        let cv = document.cookie.split('; ');
        for (let i = 0; i < cv.length; i++) {
            temp = cv[i].split('=');
            cva[temp[0]] = decodeURI(temp[1]);
        }
        return name ? cva[name] : cva;
    },

    set: function (name, value, expires, path, domain, secure) {
        if (!name || !value || name === '' || value === '') return false;
        if (expires) {
            if (/^[0-9]+$/.test(expires)) {
                let today = new Date();
                expires = new Date(today.getTime() + expires * 1000).toUTCString();
            } else if (!/^wed, \d{2} \w{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(expires)) {
                expires = undefined;
            }
        }
        let cv = name + '=' + encodeURI(value) + ';'
            + (expires ? ' expires=' + expires + ';' : '')
            + (path ? 'path=' + path + ';' : '')
            + (domain ? 'domain=' + domain + ';' : '')
            + ((secure && secure !== 0) ? 'secure' : '');
        if (cv.length < 4096) {
            document.cookie = cv;
            return true;
        } else {
            return false;
        }
    },

    move: function (name, path, domain) {
        if (!name || name === '' || !this.get(name)) return false;
        document.cookie = name + '=;'
        + (path ? 'path=' + path + ';' : '')
        + (domain ? 'domain=' + domain + ';' : '')
        + 'expires=Thu, 01-Jan-1970 00:00:01 GMT;';
        return true;
    }
};

const storage = {
    get(key) {
        if (localStorage && localStorage.getItem(key)) {
            const result = JSON.parse(localStorage.getItem(key));
            if (result.time && result.time < (new Date()).getTime()) {
                this.remove(key);
            } else {
                return result.data;
            }
        }
    },
    set(key, value, time = 0) {
        localStorage && localStorage.setItem(key, JSON.stringify({
            data: value,
            time: time ? (new Date()).getTime() + parseInt(time * 60000) : 0
        }));
    },
    remove(key) {
        localStorage.removeItem(key);
    }
};

let timer = {
    handle: null,
    start: function(callback){
        let start_minute = 0, start_second = 0;
        this.handle = setInterval(function () {
            if (start_second === 59) {
                start_second = 0;
                start_minute++;
            }
            start_second++;
            if (callback) {
                callback(zero(start_minute) + ':' + zero(start_second));
            }
        }, 1000);
    },
    stop: function(){
        clearInterval(this.handle);
    }
};

function zero(n) {
    return (n < 10 ? '0' : '') + n;
}

/**
 * @return {string}
 */
function format_time(time) {
    if (/^\d{13}$/.test(time)) {
        time = time.toString().substr(0,10);
    } else if (time.indexOf('-') !== -1 || time.indexOf(':') !== -1) {
        time = time.replace(/-/g, '/');
        time = Date.parse(time) / 1000;
    }
    if (/^\d{10}$/.test(time)) {
        let stamp = new Date();
        time = new Date(parseInt(time) * 1000);
        let H = time.getHours(), i = time.getMinutes();
        let Y = time.getFullYear(), m = time.getMonth() + 1, d = time.getDate();
        if (stamp.getFullYear() === Y) {
            if (stamp.getMonth() + 1 === m && stamp.getDate() === d) {
                return H + ':' + zero(i);
            }
            return m + '.' + d + ' ' + H + ':' + zero(i);
        }
        return Y.toString().substr(2) + '.' + m + '.' + d + ' ' + H + ':' + zero(i);
    }
    return time;
}

function ajax_post(url, data, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('token', system.token);
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.timeout = 7000;
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            callback(JSON.parse(xhr.responseText));
        }
    };
    xhr.send(JSON.stringify(data));
}

function ajax_upload(url, blog, file_name, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.timeout = 7000;
    xhr.setRequestHeader('token', system.token);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            callback(JSON.parse(xhr.responseText));
        }
    };
    let form = new FormData();
    form.append('file', blog, file_name);
    xhr.send(form);
}

//异步请求
function ajax_request(url, method, data, callback) {
    let header = {'If-Match': '1.0.0'};
    if (typeof(system.token) === 'string' && system.token !== '') {
        header.token = system.token;
    }
    if (method === 'get' && data !== null) {
        let page = 1, page_size = 20;
        if (!isNaN(parseInt(data.page))) {
            page = Math.max(page, parseInt(data.page));
        }
        if (!isNaN(parseInt(data.page_size))) {
            page_size = parseInt(data.page_size);
        }
        header.range = page + ',' + page_size;
    }

    $.ajax({
        type: method.toUpperCase(),
        url: url,
        data: data,
        dataType: 'json',
        timeout: 7000,
        headers: header,
        success: function(response){
            if (response.error === 3 || response.error === 4) {
                alert('token 失效，请重新登录');
            } else {
                callback(response);
            }
        },
        error: function(xhr, type){
            alert('服务异常，请稍后再试');
        }
    });
}

function go_foot(id, is_top = false) {
    let scroll_div = document.getElementById(id);
    scroll_div.scrollTop = is_top ? 0 : scroll_div.scrollHeight;
}